/*
 * Copyright © 2020-2021 尛飛俠（Denvie） All rights reserved.
 */

package cn.denvie.springboot.druid.utils;

import org.jasypt.properties.PropertyValueEncryptionUtils;
import org.jasypt.util.text.BasicTextEncryptor;

/**
 * Jasypt加密工具类。
 *
 * @author Denvie
 * @date 2021/7/6
 * @since 1.0.0
 */
public final class JasyptEncryptUtils {
    private static final String SALT = "denvie";
    private static final BasicTextEncryptor BASIC_TEXT_ENCRYPTOR = new BasicTextEncryptor();

    static {
        BASIC_TEXT_ENCRYPTOR.setPassword(SALT);
    }

    private JasyptEncryptUtils() {
    }

    /**
     * 加密。
     */
    public static String encrypt(String plainText) {
        System.out.println("明文字符串：" + plainText);
        String ciphertext = BASIC_TEXT_ENCRYPTOR.encrypt(plainText);
        System.out.println("加密后字符串：" + ciphertext);
        return ciphertext;
    }

    /**
     * 解密。
     */
    public static String decrypt(String cipherText) {
        System.out.println("加密字符串：" + cipherText);
        cipherText = "ENC(" + cipherText + ")";
        if (PropertyValueEncryptionUtils.isEncryptedValue(cipherText)) {
            String plaintext = PropertyValueEncryptionUtils.decrypt(cipherText, BASIC_TEXT_ENCRYPTOR);
            System.out.println("解密后的字符串：" + plaintext);
            return plaintext;
        } else {
            System.out.println("密文格式错误");
            return "";
        }
    }

    public static void main(String[] args) {
        String pwd = encrypt("root");
        decrypt(pwd);
    }
}
